#include "scanthread.h"
#include <qdebug.h>
#include <cstring>
#include <QTcpSocket>


ScanThread::ScanThread()
{

}

ScanThread::ScanThread(QString ip, int ipCount, int port, int portCount) {
    this->ip = ip;
    this->ipCount = ipCount;
    this->port = port;
    this->portCount = portCount;
}

void ScanThread::run() {

    QTcpSocket* conn = new QTcpSocket();

    QString netAddr = ip.left(ip.lastIndexOf('.') + 1);
    int hostAddr = ip.right(ip.length() - ip.lastIndexOf('.') - 1).toInt();

    QString curIP;
    int curPort;
    for(int i = 0; !isInterruptionRequested() && i < ipCount; i++) {
        curIP = netAddr + QString::number(hostAddr + i);
        for(int j = 0; !isInterruptionRequested() && j < portCount; j++) {
            qDebug() << "线程" << QThread::currentThreadId() << " 开始扫描 " << curIP << ":" << port << "\n";
            curPort = port + j;
            conn->connectToHost(curIP, curPort);
            bool res = conn->waitForConnected(1000);
            if(!isInterruptionRequested()) {
                emit scanOver(curIP + ":" + QString::number(curPort), res);
            }
            if(res) {
                qDebug() << "opened";
            } else {
                qDebug() << "closed";
            }
            conn->disconnectFromHost();
        }
    }

    qDebug() << "线程" << QThread::currentThreadId() << " 扫描完成" << "\n";
//    qDebug() << "线程" << QThread::currentThreadId() << " 提前结束" << "\n";
}
